package com.resou.reader.data.local;

import android.util.Log;

import com.resou.reader.api.entry.BaseComment;
import com.resou.reader.api.entry.LargessBook;
import com.resou.reader.api.entry.LocalPrase;
import com.resou.reader.bookshelf.readhistory.datasupport.BookCollection;
import com.resou.reader.bookshelf.readhistory.datasupport.ReaderHistory;
import com.resou.reader.data.bookshelf.model.BookShelfBook;
import com.resou.reader.data.bookshelf.model.ReadRecord;
import com.resou.reader.utils.DateUtil;
import com.resou.reader.utils.DateUtils;
import com.resou.reader.utils.log.DLog;

import org.litepal.LitePal;

import java.util.List;

import io.reactivex.disposables.Disposable;

public class LitePalHelper {
    private static LitePalHelper sInstance;

    //    public static LitePalHelper getInstance() {
//        synchronized (LitePalHelper.class) {
//            if (sInstance == null) {
//                sInstance = new LitePalHelper();
//            }
//        }
//        return sInstance;
//    }
    private static final String TAG = "LitePalHelper-App";

    public synchronized static List<BookCollection> loadShelfBooks() {
        return LitePal.order("userUpdateTime desc").find(BookCollection.class);
    }

    public synchronized static void deleteBook(BookCollection collection) {
        LitePal.deleteAll(BookCollection.class, "bookId = ?", collection.getBookId());
    }

    public synchronized static int clearBooks() {
        return LitePal.deleteAll(BookCollection.class);
    }

    public static List<ReaderHistory> loadReadHistory() {
        return LitePal.order("userUpdateTime desc").where("isDeleted = 0").find(ReaderHistory.class);//asc desc
    }

    public synchronized static ReaderHistory loadReadHistory(String bookId) {
        return LitePal.where("bookId = ?", bookId).findFirst(ReaderHistory.class);
    }
//    public static void checkAndSaveBooks(List<BookShelfBook> books) {
//        for (BookShelfBook book : books) {
//            BookCollection bookCollection = LitePal.where("bookId = ?", book.getBookId()).findFirst(BookCollection.class);
//            if (bookCollection != null) {
//                bookCollection.setAuthor(book.getAuthorName());
//                bookCollection.setBookId(book.getBookId());
//                bookCollection.setName(book.getBookName());
//                bookCollection.setPicUrl(book.getBookPic());
//                bookCollection.setSerialStatus(book.getWhetherUpdate());
//                bookCollection.setReadStatus(book.getReadStatus());
//                bookCollection.setHistoryChapterName(book.getReadStatus());
//                bookCollection.setChapterSum(book.getChapterNum());
//                if (book.getFreeStatus() == 0) {
//                    bookCollection.setFreeStatus(true);
//                } else {
//                    bookCollection.setFreeStatus(false);
//                }
//                bookCollection.setWhetherUpdate(book.getWhetherUpdate());
//                bookCollection.setUserUpdateTime(System.currentTimeMillis());
//                bookCollection.save();
//            } else {
//                BookCollection collection = new BookCollection();
//                collection.setAuthor(book.getAuthorName());
//                collection.setBookId(book.getBookId());
//                collection.setName(book.getBookName());
//                collection.setPicUrl(book.getBookPic());
//                collection.setSerialStatus(book.getWhetherUpdate());
//                collection.setReadStatus(book.getReadStatus());
//                if (book.getFreeStatus() == 0) {
//                    collection.setFreeStatus(true);
//                } else {
//                    collection.setFreeStatus(false);
//                }
//                collection.setChapterSum(book.getChapterNum());
//                collection.setHistoryChapterName(book.getReadStatus());
//                collection.setWhetherUpdate(book.getWhetherUpdate());
//                collection.setUserUpdateTime(System.currentTimeMillis());
//                collection.save();
//            }
//        }
//    }

    public synchronized static void saveLargessBooks(List<LargessBook> largessBooks) {
        for (LargessBook book : largessBooks) {
            BookCollection bookCollection = LitePal.where("bookId = ?", book.getBookId()).findFirst(BookCollection.class);
            if (bookCollection != null) {
                bookCollection.setAuthor(book.getAuthorName());
                bookCollection.setBookId(book.getBookId());
                bookCollection.setName(book.getBookName());
                bookCollection.setPicUrl(book.getBookPic());
                bookCollection.setSerialStatus(book.getWhetherUpdate());
                bookCollection.setReadStatus(book.getReadStatus());
                bookCollection.setHistoryChapterName(book.getReadStatus());
                bookCollection.setChapterSum(0);
                bookCollection.setWhetherUpdate(book.getWhetherUpdate());
                bookCollection.setUserUpdateTime(System.currentTimeMillis());
//                if (book.getFreeStatus() == 0) {
//                    bookCollection.setFreeStatus(true);
//                } else {
//                    bookCollection.setFreeStatus(false);
//                }
                bookCollection.setFreeStatus(book.getFreeStatus());
                bookCollection.save();
            } else {
                BookCollection collection = new BookCollection();
                collection.setAuthor(book.getAuthorName());
                collection.setBookId(book.getBookId());
                collection.setName(book.getBookName());
                collection.setPicUrl(book.getBookPic());
                collection.setSerialStatus(book.getWhetherUpdate());
                collection.setReadStatus(book.getReadStatus());
                collection.setChapterSum(0);
                collection.setHistoryChapterName(book.getReadStatus());
//                if (book.getFreeStatus() == 0) {
//                    collection.setFreeStatus(true);
//                } else {
//                    collection.setFreeStatus(false);
//                }
                collection.setFreeStatus(book.getFreeStatus());
                collection.setWhetherUpdate(book.getWhetherUpdate());
                collection.setUserUpdateTime(System.currentTimeMillis());
                collection.save();
            }
        }
    }

    public static synchronized void saveShelfBookBooks(List<BookShelfBook> books) {
        for (BookShelfBook book : books) {
            onlineShelfBkToCollectionBk(book);
        }
    }

    /**
     * 保存到本地
     *
     * @param books
     */
    public static synchronized void loadLocalLitePal(List<BookCollection> books) {
//        LitePalHelper.clearBooks();
        if (books == null || books.size() == 0) {
            return;
        }
        for (BookCollection book : books) {
            if (book == null) {
                return;
            }
            BookCollection bookCollection = LitePal.where("bookId = ?", book.getBookId() + "").findFirst(BookCollection.class);
            if (bookCollection == null) {
                bookCollection = new BookCollection();
            }
            bookCollection.setAuthor(book.getAuthor());
            bookCollection.setBookId(book.getBookId());
            bookCollection.setName(book.getName());
            bookCollection.setPicUrl(book.getPicUrl());
            bookCollection.setSerialStatus(book.getSerialStatus());
            bookCollection.setReadStatus(book.getReadStatus());
            bookCollection.setFreeStatus(book.getFreeStatus());
            bookCollection.setChapterSum(book.getChapterSum());
            bookCollection.setHistoryChapterName(book.getHistoryChapterName());
            bookCollection.setWhetherUpdate(book.getWhetherUpdate());
            bookCollection.setUserUpdateTime(book.getUserUpdateTime());
            bookCollection.setZsBookId(book.getZsBookId());
//            bookCollection.setChapterIndex(book.getChapterIndex());
            bookCollection.setUpdateTime(book.getUpdateTime());
            bookCollection.setLastChapterName(book.getLastChapterName());
            bookCollection.setHistoryChapterId(book.getHistoryChapterId());
            bookCollection.saveOrUpdate("bookId=?", book.getBookId());
        }
    }

    public synchronized static BookCollection onlineShelfBkToCollectionBk(BookShelfBook book) {
        BookCollection collection = LitePal.where("bookId = ?", book.getBookId()).findFirst(BookCollection.class);
        if (collection == null) {
            collection = new BookCollection();
        }
        try {
            collection.setAuthor(book.getAuthorName());
            collection.setBookId(book.getBookId());
            collection.setName(book.getBookName());
            collection.setPicUrl(book.getBookPic());
            collection.setSerialStatus(book.getWhetherUpdate());
            collection.setReadStatus(book.getReadStatus());
            collection.setFreeStatus(book.getFreeStatus());
            collection.setChapterSum(book.getChapterNum());
            collection.setHistoryChapterName(book.getReadStatus());
            collection.setWhetherUpdate(book.getWhetherUpdate());
            collection.setUserUpdateTime(System.currentTimeMillis());
            collection.setZsBookId(book.getZsBookId());
            collection.setDescription(book.getNoveldescription());
            collection.setUpdateTime(DateUtil.formatDateToLong(book.getLastUpdateTime()));
            collection.setLastChapterName(book.getLastChapterName());
            collection.setHistoryChapterId(book.getChapterId());
            collection.saveOrUpdate("bookId = ?", book.getBookId());
        } catch (Exception e) {
            Log.e(TAG, "onlineShelfBkToCollectionBk: " + e.getMessage());
        }
        return collection;
    }

    /**
     * 从极光推送入口进入，转为BookCollection
     *
     * @param book
     * @return
     */
    public synchronized static BookCollection onlineShelfBkToCollectionBk2(BookShelfBook book) {
        BookCollection collection = LitePal.where("bookId = ?", book.getBookId()).findFirst(BookCollection.class);
        if (collection == null) {
            collection = new BookCollection();
        }
        try {
            collection.setAuthor(book.getAuthorName());
            collection.setBookId(book.getBookId());
            collection.setName(book.getBookName());
            collection.setPicUrl(book.getBookPic());
            collection.setSerialStatus(book.getWhetherUpdate());
            collection.setReadStatus(book.getReadStatus());
            collection.setFreeStatus(book.getFreeStatus());
            collection.setChapterSum(book.getChapterNum());
            collection.setChapterIndex(book.getChapterIndex());
            collection.setCharIndex(0);
            collection.setHistoryChapterName(book.getReadStatus());
            collection.setWhetherUpdate(book.getWhetherUpdate());
            collection.setUserUpdateTime(System.currentTimeMillis());
            collection.setZsBookId(book.getZsBookId());
            collection.setDescription(book.getNoveldescription());
            collection.setUpdateTime(DateUtil.formatDateToLong(book.getLastUpdateTime()));
            collection.setLastChapterName(book.getLastChapterName());
            collection.setHistoryChapterId(book.getChapterId());
            collection.saveOrUpdate("bookId = ?", book.getBookId());
        } catch (Exception e) {
            Log.e(TAG, "onlineShelfBkToCollectionBk: " + e.getMessage());
        }
        return collection;
    }

    public static synchronized void saveReadRecord(List<ReadRecord.ReadRecordBean> records) {
        try{

        if (records == null)
            return;
        for (ReadRecord.ReadRecordBean record : records) {
            //创建
            ReaderHistory readerHistory = LitePal.where("bookId = ?", record.getNovelId()).findFirst(ReaderHistory.class);
            if (readerHistory == null) {
                readerHistory = new ReaderHistory();
            }
            readerHistory.setBookId(record.getNovelId());
            readerHistory.setPicUrl(record.getCoverUrl());
            readerHistory.setName(record.getNovelName());
            readerHistory.setHistoryChapterId(record.getChapterId());
            readerHistory.setHistoryChapterName(record.getChapterName());
            readerHistory.setUserUpdateTime(record.getReadTimeMs());
            readerHistory.setChapterIndex(record.getChapterIndex());
            readerHistory.setChapterSum(record.getChapterNum());
            readerHistory.setLastChapterName(record.getLastChapterName());
            readerHistory.setZsBookId(record.getZsBookId());
            readerHistory.setDeleted(false);
            readerHistory.saveOrUpdate("bookId = ?", record.getNovelId());
        }
        }catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public synchronized static void logicallyDeleteReadHistory() {
        List<ReaderHistory> histories = LitePal.findAll(ReaderHistory.class);
        for (ReaderHistory history : histories) {
            history.setDeleted(true);
            history.save();
        }
    }


    /**
     * 同步到本地点赞
     */
    public synchronized static void sysLocalPraise(List<BaseComment.DataBean> beans) {
        if (beans == null || beans.size() == 0) {
            return;
        }
        for (BaseComment.DataBean bean : beans) {
            LocalPrase localPrase = new LocalPrase();
            localPrase.setCommentId(bean.getId() + "");
            localPrase.save();
        }
    }

    /**
     * 查找本地是否点赞
     */
    public static boolean isLocalPraise(String commentId) {

//        if (commentId == null || commentId.equals("null")) {
//            return false;
//        }
//        List<LocalPrase> list = LitePal.findAll(LocalPrase.class);
//        if (list == null || list.size() == 0) {
//            return false;
//        }
//        for (LocalPrase localPrase : list) {
//            if (commentId == localPrase.getCommentId()) {
//                return true;
//            }
//        }
        return false;
    }

    /**
     * 本地点赞
     */
    public synchronized static boolean localPraise(String commentId) {
        if (commentId == null || commentId.equals("null")) {
            return false;
        }
        List<LocalPrase> list = LitePal.findAll(LocalPrase.class);
        for (LocalPrase localPrase : list) {
            if (commentId == localPrase.getCommentId()) {
                localPrase.setPraise(true);
                localPrase.saveOrUpdateAsync("commentId?=", commentId);
            }
        }
        return false;
    }
}
